<template>
  <input
    ref="uploadFile"
    type="file"
    @change="handleFileChange"
    accept="image/*"
  />

  <el-button type="button" id="uploadBtn" @click="startUpload"
    >开始上传</el-button
  >
  <div class="progress">上传进度：<span id="progressValue">0</span></div>

  <div id="uploadResult" class="result"></div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { upload } from "@/api";
const uploadFile = ref(HTMLElement);
const progressValueEle: any = document.getElementById("progressValue");
const uploadResultEle: any = document.getElementById("uploadResult");

const handleFileChange = (e: Event) => {
  const currentTarget = e.target as HTMLInputElement;
  if (currentTarget.files) {
    startUpload(currentTarget);
  }
};

const startUpload = (currentTarget: any) => {
  try {
    // 获取文件
    const file = currentTarget.files[0];
    // 创建上传数据
    const formData = new FormData();
    formData.append("file", file);
    // 上传文件
    upload(formData);
  } catch (error) {}
};
const update = async (data: any) => {
  const res = await update(data);
  console.log(res);
};
// const upload = (data: any) => {
//   const xhr = new XMLHttpRequest();
//   xhr.onreadystatechange = function () {
//     if (xhr.readyState === 4 && xhr.status === 200) {
//       const result = JSON.parse(xhr.responseText);
//       console.log("result:", result);
//       uploadResultEle.innerText = xhr.responseText;
//     }
//   };

//   // 上传进度
//   xhr.upload.onprogress = function (event) {
//     if (event.lengthComputable) {
//       progressValueEle.innerText =
//         Math.ceil((event.loaded * 100) / event.total) + "%";
//     }
//   };

//   xhr.open("POST", "http://127.0.0.1:8000/files/upload", true);
//   xhr.send(data);
// };
</script>